package prototype.autosurfer;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Logger;

import net.m510.autosurfer.core.DocumentResponseHandler;
import net.m510.autosurfer.core.Parameters;
import net.m510.autosurfer.core.process.AbstractSurfProcess;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.jsoup.nodes.Document;

public class NextProcess extends AbstractSurfProcess {
	private static final Logger log = Logger.getLogger(NextProcess.class.getName());

	public NextProcess() {
		super();
	}
	public NextProcess(CloseableHttpClient cl, HttpClientContext ctx) {
		super(cl, ctx);
	}

	@Override
	public Document process(Document doc) throws ClientProtocolException,
			IOException {
		//　リクエストパラメータ設定
		Parameters params = Parameters.create(doc.getAllElements().forms().get(0));
//		params.put("q", new String("IT屋として生きる".getBytes("SHIFT_JIS")));
//		params.put("q", new String("ＩＴ屋として生きる".getBytes("SHIFT_JIS"),"SHIFT_JIS"));
		params.put("q", "IT屋として生きる");
		params.remove("btnI");
		log.info("param q="+params.get("q"));
		byte[] b = params.get("q").getBytes();
		String s = new String();
		for (int i = 0; i < b.length; i++) {
			s = String.format("%s %02x", s,b[i]);
		}
		log.info("param(bytes) q="+s);
		//
		URIBuilder builder = new URIBuilder(URI.create("http://www.google.com/search"));
//		SafetyURIBuilder builder = new SafetyURIBuilder(URI.create("http://www.google.com/search"));
		builder.addParameters(params.asNameValueList());
		URI uri = null;
		try {
			uri = builder.build();
		} catch (URISyntaxException e) {
			throw new IllegalStateException(e);
		}
		
//		HttpUriRequest req = RequestBuilder.get().setHeader("Content-type", "charset=UTF-8").setUri(uri).build();
		HttpGet req = new HttpGet(uri);
		
		ResponseHandler<Document> rh = new DocumentResponseHandler();
		Document out = client.execute(req,rh,context);
		log.info("response doc="+out.html());
		return out;
	}

}
